package com.bdqn.business.academic.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.business.academic.dao.ChapterMapper;
import com.bdqn.business.academic.dao.SingleMapper;
import com.bdqn.entity.academic.Chapter;
import com.bdqn.entity.academic.Single;
import com.bdqn.response.PageResult;
import com.bdqn.response.Result;
import com.bdqn.response.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service
@Transactional
public class SingleService {

    @Autowired
    private SingleMapper singleMapper;

    @Autowired
    private ChapterMapper chapterMapper;

    public Result getList(Map<String, Object> map) {

        Integer page = Integer.parseInt(map.get("page").toString());
        Integer size = Integer.parseInt(map.get("size").toString());

        QueryWrapper<Single> queryWrapper = new QueryWrapper<>();

        queryWrapper.orderByDesc("create_time");

        IPage<Single> singleIPage = new Page<>(page,size);

        IPage<Single> result = singleMapper.selectPage(singleIPage, queryWrapper);

        PageResult<Single> pageResult = new PageResult<>(result.getTotal(),result.getRecords());

        return new Result(ResultCode.SUCCESS,pageResult);

    }

    @CachePut(cacheNames = "single",key = "#single.id")
    public Result saveSingle(Single single) {
        Chapter chapter = chapterMapper.selectById(single.getChapterId());
        single.setChapterName(chapter.getName());
        single.setStatus("1"); //启用
        single.setCreateTime(new Date());


        if(single.getSingleContent().contains("<img")){
            single.setSingleContent(single.getSingleContent().replaceAll("<img","<img width='300px' height='300px' "));
        }

        singleMapper.insert(single);
        return new Result(ResultCode.SUCCESS,single);
    }
}
